package ie.lawlor.amvc.component.piechart;

import ie.lawlor.amvc.event.Event;
import ie.lawlor.amvc.swing.JPanelView;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;



/**
 * @author blawlor
 *
 */
public class PieChartView extends JPanelView {
	
  JFreeChart chart;
  ChartPanel chartPanel;
  DefaultPieDataset dataset = new DefaultPieDataset();
	
  public PieChartView() {
    super();
  }
  
  public PieChartView(String name) {
    super(name);
    initComponents();
  }
  
	public void initComponents(){
    logger.debug("Initializing the chart view");
    chart = ChartFactory.createPieChart3D("",
            dataset,
            true, true, false);
    chartPanel = new ChartPanel(chart);
    add(chartPanel);
	}
  
  public void doUpdateView(Event e) {
    logger.debug("Entering");
    updatingView = true;
    PieChartModel model = (PieChartModel) e.getPayload();
    refreshData(model);
    chart = ChartFactory.createPieChart3D(model.getPieTitle(),
            dataset,
            true, true, false);
    chartPanel.setChart(chart);
    updatingView = false;
  }
  
  private void refreshData(PieChartModel model){
    dataset = new DefaultPieDataset();
    for (int i = 0; i < model.getSliceNames().length; ++i){
      dataset.setValue(model.getSliceNames()[i], model.getSliceValues()[i]);
    }
  }
	
}
